package com.zhida.jiyangcenter.order

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import chooongg.base.annotation.ContentLayout
import chooongg.base.annotation.TitleBar
import chooongg.base.utils.*
import chooongg.base.widget.recyclerView.divider.HorizontalDividerItemDecoration
import chooongg.base.widget.recyclerView.divider.VerticalDividerItemDecoration
import chooongg.http.APIException
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.gson.Gson
import com.zhida.jiyangcenter.R
import com.zhida.jiyangcenter.address.AddAddressActivity
import com.zhida.jiyangcenter.address.AddressListActivity
import com.zhida.jiyangcenter.api.*
import com.zhida.jiyangcenter.mian.BaseActivity
import com.zhida.jiyangcenter.utils.*
import com.zhida.jiyangcenter.widget.SmoothCheckBox
import kotlinx.android.synthetic.main.activity_confirm_order.*
import java.math.RoundingMode

@TitleBar(false)
@ContentLayout(R.layout.activity_confirm_order)
class ConfirmOrderActivity : BaseActivity() {
    val adapter = Adapter()
    val adapterServe = AdapterServe()
    var addressUUID = ""
    override fun initConfig(savedInstanceState: Bundle?) {
        title_bar.title("确认订单").navigationIcon(R.drawable.iv_back_fill) {
            finish()
        }
        rv_confirm_order.layoutManager = object : LinearLayoutManager(context) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        rv_confirm_order.addItemDecoration(
            HorizontalDividerItemDecoration.Builder(context)
                .sizeResId(R.dimen.dividerBig).colorResId(R.color.colorBack).build()
        )
        when (intent.getStringExtra("type")) {
            "ShopCar" -> {
                rv_confirm_order.adapter = adapter
            }
            "ShopDetails" -> {
                rv_confirm_order.adapter = adapter
            }
            "ServeDetails" -> {
                rv_confirm_order.adapter = adapterServe
            }
        }
        adapterServe.setOnItemChildClickListener { _, view, position ->
            if (productOrderEntity.coupon_list.isNullOrEmpty()) {
                toast("您还没有优惠券可以使用哦")
            } else {
                val bottomSheetDialog =
                    BottomSheetDialog(context, R.style.BottomSheetDialog)
                val view =
                    layoutInflater.inflate(
                        R.layout.dialog_confirm_order_coupon,
                        null,
                        false
                    )
                view.findViewById<TextView>(R.id.iv_close)
                    .setOnClickListener { bottomSheetDialog.dismiss() }
                val scb_buy_car = view.findViewById<SmoothCheckBox>(R.id.scb_buy_car)
                scb_buy_car.setOnClickListener {

                    adapterServe.data[position].coupon_id = ""
                    adapterServe.data[position].coupon_money = 0
                    adapterServe.notifyItemChanged(position)

                    money = total_money
                    tv_confirm_order_submit_money.text = "合计：￥${money}"
                    bottomSheetDialog.dismiss()
                }
                scb_buy_car.setChecked(adapterServe.data[position].coupon_id == "", true)
                val rv_dialog = view.findViewById<RecyclerView>(R.id.rv_dialog)
                rv_dialog.addItemDecoration(
                    HorizontalDividerItemDecoration.Builder(context)
                        .sizeResId(R.dimen.dividerSmall).colorResId(R.color.colorBack)
                        .build()
                )
                rv_dialog.layoutManager = LinearLayoutManager(context)
                rv_dialog.adapter = AdapterCoupon().apply {
                    setNewData(productOrderEntity.coupon_list)

                    coupon_uuid = adapterServe.data[position].coupon_id ?: ""
                    setOnItemClickListener { _, view, index ->
                        adapterServe.data[position].coupon_id = data[index].uuid
                        adapterServe.data[position].coupon_money =
                            if (data[index].classification == "1") data[index].reduction else data[index].reduction
                        money = if (data[index].classification == "1") {
                            bigDecimalReduce(total_money, data[index].reduction!!.toDouble())
                        } else {
                            bigDecimalReduce(total_money, data[index].immediately!!.toDouble())
                        }
                        tv_confirm_order_submit_money.text = "合计：￥${money}"
                        adapterServe.notifyItemChanged(position)
                        bottomSheetDialog.dismiss()
                    }

                }
                bottomSheetDialog.setContentView(view)
                bottomSheetDialog.show()
            }

        }
        adapter.setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.rl_confirm_order_store -> {
                    val bottomSheetDialog = BottomSheetDialog(context, R.style.BottomSheetDialog)
                    val view =
                        layoutInflater.inflate(R.layout.dialog_confirm_order_goods, null, false)
                    val rv_dialog = view.findViewById<RecyclerView>(R.id.rv_dialog)
                    rv_dialog.addItemDecoration(
                        HorizontalDividerItemDecoration.Builder(context)
                            .sizeResId(R.dimen.dividerSmall).colorResId(R.color.colorBack).build()
                    )
                    rv_dialog.layoutManager = LinearLayoutManager(context)
                    rv_dialog.adapter = DialogAdapter().apply {
                        setNewData(ArrayList<String>().apply {
                            add("kasj")
                            add("kasj")
                            add("kasj")
                            add("kasj")
                        })
                    }
                    bottomSheetDialog.setContentView(view)
                    bottomSheetDialog.show()
                }
                R.id.btn_coupon -> {

                    val bottomSheetDialog =
                        BottomSheetDialog(context, R.style.BottomSheetDialog)
                    val view =
                        layoutInflater.inflate(
                            R.layout.dialog_confirm_order_coupon,
                            null,
                            false
                        )
                    view.findViewById<TextView>(R.id.iv_close)
                        .setOnClickListener { bottomSheetDialog.dismiss() }
                    val scb_buy_car = view.findViewById<SmoothCheckBox>(R.id.scb_buy_car)
                    scb_buy_car.setOnClickListener {
                        money = bigDecimalAdd(
                            money,
                            (adapter.data[position].coupon_money ?: 0).toDouble()
                        )
                        when (intent.getStringExtra("type")) {
                            "ShopCar" -> {
                                adapter.data[position].coupon_id = ""
                                adapter.data[position].coupon_money = 0
                                adapter.notifyItemChanged(position)
                            }
                            "ShopDetails" -> {
                                adapter.data[position].coupon_id = ""
                                adapter.data[position].coupon_money = 0
                                adapter.notifyItemChanged(position)
                            }
                        }

                        tv_confirm_order_submit_money.text = "合计：￥${money}"
                        bottomSheetDialog.dismiss()
                    }
                    when (intent.getStringExtra("type")) {
                        "ShopCar" -> {
                            scb_buy_car.setChecked(adapter.data[position].coupon_id == "", true)
                        }
                        "ShopDetails" -> {
                            scb_buy_car.setChecked(adapter.data[position].coupon_id == "", true)
                        }
                    }
                    val rv_dialog = view.findViewById<RecyclerView>(R.id.rv_dialog)
                    rv_dialog.addItemDecoration(
                        HorizontalDividerItemDecoration.Builder(context)
                            .sizeResId(R.dimen.dividerSmall).colorResId(R.color.colorBack)
                            .build()
                    )
                    rv_dialog.layoutManager = LinearLayoutManager(context)
                    when (intent.getStringExtra("type")) {
                        "ShopCar" -> {
                            lifecycleScope.request({
                                APIShop.service().productCouponList(
                                    adapter.data[position].product ?: "",
                                    adapter.data[position].num ?: 1
                                )
                            }, object : BaseAPI<List<ProductOrderEntity.CouponList>>() {
                                override fun onSuccess(
                                    t: List<ProductOrderEntity.CouponList>?,
                                    state: Int,
                                    msg: String
                                ) {
                                    if (t.isNullOrEmpty()) {
                                        toast("您还没有优惠券可以使用哦")
                                    } else {
                                        rv_dialog.adapter = AdapterCoupon().apply {
                                            setNewData(t)
                                            coupon_uuid = adapter.data[position].coupon_id ?: ""
                                            setOnItemClickListener { _, view, index ->
                                                adapter.data[position].coupon_id = data[index].uuid
                                                adapter.data[position].coupon_money =
                                                    if (data[index].classification == "1") data[index].reduction else data[index].reduction
                                                money = if (data[index].classification == "1") {
                                                    total_money - data[index].reduction!!
                                                } else {
                                                    total_money - data[index].immediately!!
                                                }
                                                tv_confirm_order_submit_money.text = "合计：￥${money}"
                                                adapter.notifyItemChanged(position)
                                                bottomSheetDialog.dismiss()
                                            }
                                        }
                                        bottomSheetDialog.setContentView(view)
                                        bottomSheetDialog.show()
                                    }

                                }

                                override fun onError(e: APIException) {
                                    tipFail(e.eMessage)
                                }

                            })
                        }
                        "ShopDetails" -> {
                            if (productOrderEntity.coupon_list.isNullOrEmpty()) {
                                toast("您还没有优惠券可以使用哦")
                            } else {
                                rv_dialog.adapter = AdapterCoupon().apply {
                                    setNewData(productOrderEntity.coupon_list)
                                    coupon_uuid = adapter.data[position].coupon_id ?: ""
                                    setOnItemClickListener { _, view, index ->
                                        adapter.data[position].coupon_id = data[index].uuid
                                        adapter.data[position].coupon_money =
                                            if (data[index].classification == "1") data[index].reduction else data[index].reduction
                                        money = if (data[index].classification == "1") {
                                            total_money - data[index].reduction!!
                                        } else {
                                            total_money - data[index].immediately!!
                                        }
                                        tv_confirm_order_submit_money.text = "合计：￥${money}"
                                        adapter.notifyItemChanged(position)
                                        bottomSheetDialog.dismiss()
                                    }
                                }
                                bottomSheetDialog.setContentView(view)
                                bottomSheetDialog.show()
                            }
                        }

                    }


                }
            }
        }
        iv_confirm_order_address.setOnClickListener {
            startActivityForResult(Intent(this,AddressListActivity::class.java).apply {
                putExtra("type", "confirm")
            },12)
        }
        tv_confirm_order_name.setOnClickListener {
            startActivityForResult(Intent(this,AddressListActivity::class.java).apply {
                putExtra("type", "confirm")
            },12)
        }
        tv_confirm_order_address.setOnClickListener {
            startActivityForResult(Intent(this,AddressListActivity::class.java).apply {
                putExtra("type", "confirm")
            },12)
        }
        tv_confirm_order_address_more.setOnClickListener {
            startActivityForResult(Intent(this,AddressListActivity::class.java).apply {
                putExtra("type", "confirm")
            },12)
        }
        tv_confirm_order_address_null.setOnClickListener {
            startActivityForResult(Intent(this,AddressListActivity::class.java).apply {
                putExtra("type", "confirm")
            },12)
        }
        tv_confirm_order_submit.setOnClickListener {
            when (intent.getStringExtra("type")) {
                "ShopCar" -> {
                    val product = ArrayList<OrderPrams.ProductPrams>()
                    adapter.data.forEach {
                        product.add(
                            OrderPrams.ProductPrams(
                                it.product ?: "",
                                it.num ?: 1,
                                it?.coupon_id ?: ""
                            )
                        )
                    }
                    val orderPrams =
                        OrderPrams(addressUUID, money, product)
                    lifecycleScope.request({
                        APIShop.service().productOrderCarSubmit(Gson().toJson(orderPrams))
                    },
                        object : BaseAPI<ProductOrderSubmitEntity>() {
                            override fun onSuccess(
                                t: ProductOrderSubmitEntity?,
                                state: Int,
                                msg: String
                            ) {
                                tipSuccess(msg)
                                startActivity<PayOrderActivity> {
                                    putExtra("orderCode", t?.code)
                                    putExtra("total_money", t?.total_money)
                                    putExtra("kind", "0")
                                }
                            }

                            override fun onError(e: APIException) {
                                tipFail(e.eMessage)
                            }

                        })
                }
                "ShopDetails" -> {
                    var productUUID = ""
                    adapter.data.forEach {
                        productUUID += if (productUUID.isEmpty())
                            it.product
                        else "," + it.product
                    }
                    lifecycleScope.request({
                        APIShop.service()
                            .productOrderSubmit(
                                productUUID,
                                addressUUID,
                                productOrderEntity.product?.get(0)?.coupon_id ?: "",
                                1,
                                money
                            )
                    }, object : BaseAPI<ProductOrderSubmitEntity>() {
                        override fun onSuccess(
                            t: ProductOrderSubmitEntity?,
                            state: Int,
                            msg: String
                        ) {
                            tipSuccess(msg)
                            startActivity<PayOrderActivity> {
                                putExtra("orderCode", t?.code)
                                putExtra("total_money", t?.total_money)
                                putExtra("kind", "0")
                            }
                        }

                        override fun onError(e: APIException) {
                            tipFail(e.eMessage)
                        }
                    })
                }
                "ServeDetails" -> {
                    var serveUUID = ""
                    adapterServe.data.forEach {
                        serveUUID += if (serveUUID.isEmpty())
                            it.serve
                        else "," + it.serve
                    }
                    lifecycleScope.request({
                        APIShop.service().serveOrderSubmit(
                            serveUUID,
                            money,
                            adapterServe.data.get(0)?.coupon_id ?: ""
                        )
                    }, object : BaseAPI<ProductOrderSubmitEntity>() {
                        override fun onSuccess(
                            t: ProductOrderSubmitEntity?,
                            state: Int,
                            msg: String
                        ) {
                            tipSuccess(msg)
                            startActivity<PayOrderActivity> {
                                putExtra("orderCode", t?.code)
                                putExtra("total_money", t?.total_money)
                                putExtra("kind", "4")
                            }
                        }

                        override fun onError(e: APIException) {
                            tipFail(e.eMessage)
                        }

                    })
                }
                else -> {

                }
            }
        }
        getData()
    }

    lateinit var productOrderEntity: ProductOrderEntity
    var freight = 0.00
    var couponMoney = 0.00
    var total_money = 0.00
    var money = 0.00
    private fun getData() {
        lifecycleScope.request({
            when (intent.getStringExtra("type")) {
                "ShopDetails" -> {
                    APIShop.service().productOrder(intent.getStringExtra("uuid") ?: "")
                }
                "ShopCar" -> {
                    APIShop.service().productCarOrder(intent.getStringExtra("uuid") ?: "")
                }
                "ServeDetails" -> {
                    APIShop.service().serveOrder(intent.getStringExtra("uuid") ?: "")
                }
                else -> {
                    APIShop.service().productOrder(intent.getStringExtra("uuid") ?: "")
                }
            }

        }, object : BaseAPI<ProductOrderEntity>() {
            @SuppressLint("SetTextI18n")
            override fun onSuccess(t: ProductOrderEntity?, state: Int, msg: String) {
                if (t == null) {

                } else {
                    productOrderEntity = t
                    addressUUID = productOrderEntity.address?.uuid ?: ""
                    if (t.address?.area != null && t.address.name != null && t.address.phone != null) {
                        iv_confirm_order_address.visible()
                        tv_confirm_order_name.visible()
                        tv_confirm_order_address.visible()
                        tv_confirm_order_address_more.visible()
                        tv_confirm_order_address_null.gone()
                        tv_confirm_order_name.text = "收货人：${t.address.name}     ${t.address.phone}"
                        tv_confirm_order_address.text = t.address.area + t.address.detail
                    } else {
                        iv_confirm_order_address.gone()
                        tv_confirm_order_name.gone()
                        tv_confirm_order_address.gone()
                        tv_confirm_order_address_more.gone()
                        tv_confirm_order_address_null.visible()
                    }
                    when (intent.getStringExtra("type")) {
                        "ShopCar" -> {
                            adapter.setNewData(t.product)
                            total_money = t.total_money!!
                            t.product?.forEach {
                                freight += it.up_money!!
                            }
                            money = total_money - couponMoney
                        }
                        "ShopDetails" -> {
                            adapter.setNewData(t.product)
                            total_money = t.total_money!!
                            t.product?.forEach {
                                freight += it.up_money!!
                            }
                            money = total_money - couponMoney
                        }
                        "ServeDetails" -> {
                            tv_confirm_order_money1.text = "服务金额"
                            adapterServe.setNewData(t.serve)
                            total_money = t.total_money!!
                            money = total_money - couponMoney
                            rl_confirm_order_freight.gone()
                            cl_address.gone()
                        }
                    }
                    tv_confirm_order_submit_money.text = "合计：￥${money}"
                    tv_confirm_order_money.text = "￥${total_money - freight}"
                    tv_confirm_order_freight.text = "￥${freight}"

                }

            }

            override fun onError(e: APIException) {
                tipFail(e.eMessage)
            }

        })
    }

    class DialogAdapter :
        BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_item_confirm_order) {
        override fun convert(helper: BaseViewHolder, item: String?) {

        }

    }

    class AdapterServe :
        BaseQuickAdapter<ProductOrderEntity.Serve, BaseViewHolder>(R.layout.item_confirm_order) {
        override fun convert(helper: BaseViewHolder, item: ProductOrderEntity.Serve?) {
            val cl_confirm_order_goods1 =
                helper.getView<ConstraintLayout>(R.id.cl_confirm_order_goods1)
            val rl_confirm_order_store = helper.getView<LinearLayout>(R.id.rl_confirm_order_store)
            helper.addOnClickListener(R.id.rl_confirm_order_store)
                .addOnClickListener(R.id.btn_coupon)
            glideImage(helper.getView(R.id.niv_shop_order), item?.pic ?: "")
            helper.setText(R.id.tv_shop_order_name, item?.name)
                .setText(R.id.tv_shop_order_num, "x" + item?.num)
                .setText(R.id.tv_shop_order_money, "￥" + item?.price)
                .setGone(R.id.tv_confirm_order_store_name, false)
                .setText(R.id.tv_confirm_order_coupon, "￥" + (item?.coupon_money ?: 0))
                .setBackgroundRes(R.id.cl_confirm_order_goods1, R.color.white)
                .setGone(R.id.rl_confirm_order_freight, false)
            rl_confirm_order_store.gone()
            cl_confirm_order_goods1.visible()
        }
    }

    class Adapter :
        BaseQuickAdapter<ProductOrderEntity.Product, BaseViewHolder>(R.layout.item_confirm_order) {
        override fun convert(helper: BaseViewHolder, item: ProductOrderEntity.Product?) {
//            val rv_confirm_order_store = helper.getView<RecyclerView>(R.id.rv_confirm_order_store)
            val cl_confirm_order_goods1 =
                helper.getView<ConstraintLayout>(R.id.cl_confirm_order_goods1)
            val rl_confirm_order_store = helper.getView<LinearLayout>(R.id.rl_confirm_order_store)
            helper.addOnClickListener(R.id.rl_confirm_order_store)
                .addOnClickListener(R.id.btn_coupon)
            glideImage(helper.getView(R.id.niv_shop_order), item?.pic ?: "")
            helper.setText(R.id.tv_shop_order_name, item?.name)
                .setText(R.id.tv_shop_order_num, "x" + item?.num)
                .setText(R.id.tv_shop_order_money, "￥" + item?.price)
                .setGone(R.id.tv_confirm_order_store_name, false)
                .setText(R.id.tv_confirm_order_coupon, "￥" + (item?.coupon_money ?: 0))
                .setBackgroundRes(R.id.cl_confirm_order_goods1, R.color.white)
            if (item?.is_up == true) {
                helper.setText(R.id.tv_confirm_order_freight, "快递免邮")
            } else {
                helper.setText(R.id.tv_confirm_order_freight, "快递 ￥${item?.up_money}")
            }
//            if (helper.layoutPosition % 2 == 0) {
//                rl_confirm_order_store.visible()
//                cl_confirm_order_goods1.gone()
//                rl_confirm_order_num.gone()
//                rv_confirm_order_store.layoutManager =
//                    LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false)
//                rv_confirm_order_store.addItemDecoration(
//                    VerticalDividerItemDecoration.Builder(
//                        mContext
//                    ).sizeResId(R.dimen.dividerBig).colorResId(R.color.white).build()
//                )
//                val adapter = GoodsAdapter()
//                rv_confirm_order_store.adapter = adapter
//                adapter.setNewData(ArrayList<String>().apply {
//                    add("aksj")
//                    add("aksj")
//                    add("aksj")
//                    add("aksj")
//                    add("aksj")
//                    add("aksj")
//                    add("aksj")
//                    add("aksj")
//                    add("aksj")
//                    add("aksj")
//                })
//            } else {
            rl_confirm_order_store.gone()
            cl_confirm_order_goods1.visible()

//            }
        }

        class GoodsAdapter :
            BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_confirm_order_goods) {
            override fun convert(helper: BaseViewHolder, item: String?) {

            }

        }
    }

    class AdapterCoupon :
        BaseQuickAdapter<ProductOrderEntity.CouponList, BaseViewHolder>(R.layout.item_dialog_confirm_coupon) {
        var coupon_uuid = ""
        override fun convert(helper: BaseViewHolder, item: ProductOrderEntity.CouponList?) {
            helper.getView<SmoothCheckBox>(R.id.scb_buy_car)
                .setChecked(item?.uuid == coupon_uuid, true)
            glideImage(helper.getView(R.id.iv_my_coupon_cover), item?.picture ?: "")
            helper.setText(R.id.tv_coupon_time, item?.start_time + "-" + item?.end_time)
            if (item?.classification == "1") {
                helper.setText(R.id.tv_my_coupon_money, item.name)
            } else {
                helper.setText(R.id.tv_my_coupon_money, "立减${item?.immediately}元")
            }
        }

    }

    @SuppressLint("SetTextI18n")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 12 && resultCode == 10) {
            if (data != null) {
                addressUUID = data.getStringExtra("uuid") ?: ""
                iv_confirm_order_address.visible()
                tv_confirm_order_name.visible()
                tv_confirm_order_address.visible()
                tv_confirm_order_address_more.visible()
                tv_confirm_order_address_null.gone()
                tv_confirm_order_name.text =
                    "收货人：${data.getStringExtra("name")}     ${data.getStringExtra("phone")}"
                tv_confirm_order_address.text =
                    data.getStringExtra("area") + data.getStringExtra("detail")
            }
        }
    }
}